package com.hsurosy.domain.activity.service.quota.rule.impl;

import com.hsurosy.domain.activity.model.entity.ActivityCountEntity;
import com.hsurosy.domain.activity.model.entity.ActivityEntity;
import com.hsurosy.domain.activity.model.entity.ActivitySkuEntity;
import com.hsurosy.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import com.hsurosy.domain.activity.repository.IActivityRepository;
import com.hsurosy.domain.activity.service.armory.IActivityDispatch;
import com.hsurosy.domain.activity.service.quota.rule.AbstractActionChain;
import com.hsurosy.types.enums.ResponseCode;
import com.hsurosy.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author Hsu琛君珩
 * @Date 2024-11-08 18:35
 * @Description 商品库存规则节点
 * @Version: v1.0.0
 */
@Slf4j
@Component("activity_sku_stock_action")
public class ActivitySkuStockActionChain extends AbstractActionChain {

    @Resource
    private IActivityRepository activityRepository;
    @Resource
    private IActivityDispatch activityDispatch;

    /**
     * 校验并扣减活动 SKU 的库存，并将扣减记录发送至延迟队列。
     *
     * @param activitySkuEntity 活动 SKU 实体
     * @param activityEntity 活动实体
     * @param activityCountEntity 活动次数实体
     * @return 扣减成功返回 true
     * @throws AppException 当库存不足或扣减失败时，抛出异常
     */
    @Override
    public boolean action(ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity) {
        log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】开始。sku: {} activityId: {}", activitySkuEntity.getSku(), activityEntity.getActivityId());

        // 尝试扣减库存
        boolean status = activityDispatch.subtractionActivitySkuStock(activitySkuEntity.getSku(), activityEntity.getEndDateTime());

        // 扣减成功时，记录并发送至延迟队列
        if (status) {
            log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】成功。sku: {} activityId: {}", activitySkuEntity.getSku(), activityEntity.getActivityId());

            // 将扣减信息发送至延迟队列，以便后续更新库存
            activityRepository.activitySkuStockConsumeSendQueue(ActivitySkuStockKeyVO.builder()
                    .sku(activitySkuEntity.getSku())
                    .activityId(activityEntity.getActivityId())
                    .build());

            return true;
        }

        // 扣减失败时，抛出库存不足异常
        throw new AppException(ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getCode(), ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getInfo());
    }

}
